package com.ruoyi.common;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;

public class Snippet {
	public static void main(String[] args) {
		exportExcel();
	}
	
	public static void exportExcel(){
	        long startTime = System.currentTimeMillis();
	        System.err.println("exportExcel："+startTime);
	        String excelName = "超大用户数据";

	        String exportPath = "D:\\java_project\\mall\\";
	        boolean isRun = true;
	        int size = 1048575;//104 * 10000;
	        
	        int page = 0;
	        int sheetDataSize = 0;
	        int sheetNo = 0;
	        FileOutputStream outputStream = null;
	        try {
	            outputStream = new FileOutputStream(exportPath + excelName + ".xlsx");
	            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
	            do {
	                page++;
	                List<User> openList = getUsersByPage((page - 1) * size, size);
	                if(openList==null || openList.size()==0){
	                    isRun = false;
	                    break;
	                }
	                sheetDataSize += openList.size();
	                if(sheetDataSize > 1000000){
	                    sheetNo++;
	                    sheetDataSize = openList.size();
	                }
	                //写入文件流
	                WriteSheet writeSheet = EasyExcel.writerSheet(sheetNo, "channel-"+sheetNo).head(User.class)
	                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
	                excelWriter.write(openList, writeSheet);
	            }while (isRun);
	            excelWriter.finish();
	            outputStream.flush();
	        }catch (IOException e){
	            e.printStackTrace();
	        }finally {
	            if (outputStream != null) {
	                try {
	                    outputStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            System.err.println(sheetDataSize+ "exportExcel结束执行时间："+(System.currentTimeMillis()-startTime));
	        }
}
	
	private static List<User>  getUsersByPage(int page, int pageSize) {
	List<User> list = new ArrayList<User>();
	for (int i = page; i < pageSize; i++) {
		list.add(new User("张三"+i, 28+i));
	}
	
    return list;
}
}

